package com.demo.util;

import org.apache.commons.lang3.StringUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.demo.exception.SystemException;

public class JSONUtils {
	static {
		JSON.DEFFAULT_DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";
	}

	public static String serialize(Object obj){
		String ret = "";
		try {
			ret = JSON.toJSONString(obj,SerializerFeature.WriteDateUseDateFormat,SerializerFeature.DisableCircularReferenceDetect);
		} catch (Exception e) {
			throw new SystemException("JSON序列化结果异常:" + e.getMessage());
		}

		return ret;
	}

	public static <T> T deserialize(String jsonStr, Class<T> clazz){
		if (StringUtils.isBlank(jsonStr)) {
			return null;
		}
		try {
			return JSON.parseObject(jsonStr.replace("\n", ""), clazz);
		} catch (Exception e) {
			throw new SystemException("JSON反序列化结果异常:" + e.getMessage());
		}
	}
	
//	private static ObjectMapper mapper = new ObjectMapper();
//
//	static {
//		mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
//	}
//
//	public static String serialize(Object obj){
//		StringWriter writer = null;
//		try {
//			writer = new StringWriter();
//			mapper.writeValue(writer, obj);
//			writer.close();
//		} catch (Exception e) {
//			throw new SystemException("JSON序列化结果异常:" + e.getMessage());
//		}
//
//		return writer.toString();
//	}
//
//	public static <T> T deserialize(String jsonStr, Class<T> clazz){
//		if (StringUtils.isBlank(jsonStr)) {
//			return null;
//		}
//		try {
//			return mapper.readValue(jsonStr.replace("\n", ""), clazz);
//		} catch (Exception e) {
//			throw new SystemException("JSON反序列化结果异常:" + e.getMessage());
//		}
//		
//	}
}